<template>
  <div class="app-container-flex">
    <NewFullScreen v-model="showDialog" :title="title">
      <template v-slot:full-button>
        <el-button
          @click="saveAndSubmit()"
          v-if="
            !orderId && $permission('consignConsumeConfirmOrder:saveAndSubmit')
          "
          >保存并提交</el-button
        >
        <el-button @click="save()">保存</el-button>
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-depotName>
              <el-input
                class="not-mongolia"
                type="input"
                :required="true"
                :disabled="true"
                placeholder="请选择消耗仓库"
                v-model="formInfo.data.depotName"
              >
                <template #append>
                  <el-icon @click="selectStoreDepot"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-consumeDeptName>
              <el-input
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择消耗部门"
                v-model="formInfo.data.consumeDeptName"
              >
                <template #append>
                  <el-icon @click="selectConsumeDept"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-supplierName>
              <el-input
                type="input"
                :disabled="true"
                class="not-mongolia"
                placeholder="请选择供应商"
                v-model="formInfo.data.supplierName"
              >
                <template #append>
                  <el-icon @click="openSupplierWindow"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </page-form>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')"></Tooltip>
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <div class="filter-wrapper">
            <page-filter :filter-list="filterInfo.list">
              <template v-slot:filter-addProduct>
                <el-button :disabled="!canAddProduct" @click="addProduct"
                  >添加产品</el-button
                >
              </template>
              <template v-slot:filter-removeProduct>
                <el-button
                  :disabled="!canRemoveProduct"
                  @click="removeProduct()"
                  >删除产品</el-button
                >
              </template>
            </page-filter>
          </div>

          <div class="flex_full_item">
            <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summaryFieldList="tableInfo.summaryFieldList"
                :tabIndex="true"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :row-class-name="tableRowClassName"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-price="scope">
                  <template v-if="!tableInfo.isSysGroup">
                    <el-form-item
                      @click.stop=""
                      :prop="`data.${scope.$index}.price`"
                      :rules="
                        scope.$index >= 0
                          ? {
                              validator: $validate.positiveMoneyZero,
                              trigger: 'blur',
                            }
                          : {}
                      "
                    >
                      <el-input-number
                        v-model="scope.row.price"
                        controls-position="right"
                        :precision="
                          $store.state.permission.systemConfig.price_precision
                        "
                        :min="0"
                        :max="999999999999999"
                      />
                    </el-form-item>
                  </template>
                  <span v-else>{{
                    $fn.TripartiteMethod(scope.row.price)
                  }}</span>
                </template>
                <template v-slot:col-qty="scope">
                  <template v-if="!tableInfo.isSysGroup">
                    <el-form-item
                      class="margin-bottom"
                      v-if="
                        scope.row.codeType === 1 || scope.row.codeType === 4
                      "
                    >
                      <div class="page-table-input-number-wrapper">
                        <div class="page-table-input-number-left">
                          <div class="page-table-input-number-item">
                            <el-form-item
                              :prop="`data.${scope.$index}.largeUnitQty`"
                              :rules="
                                scope.$index >= 0
                                  ? [
                                      {
                                        validator: $validate.positiveAndZero,
                                        trigger: 'blur',
                                      },
                                    ]
                                  : []
                              "
                            >
                              <el-input-number
                                style="width: 100%; margintop: 18px"
                                v-model.lazy="scope.row.largeUnitQty"
                                clearable
                                :disabled="true"
                                controls-position="right"
                                :precision="
                                  scope.row.qtyOperateMode === 0 ||
                                  scope.row.qtyOperateMode === 2
                                    ? 0
                                    : systemConfig.qty_show_precision
                                "
                                @change="
                                  changeLarge(
                                    $event,
                                    scope.row,
                                    `data.${scope.$index}.largeUnitQty`
                                  )
                                "
                                :min="0"
                                :max="scope.row.availableConfirmQty"
                              />
                            </el-form-item>
                            <div class="page-table-input-number-item-unite">
                              {{ scope.row.unitName }}
                            </div>
                          </div>
                          <div
                            class="page-table-input-number-item"
                            v-if="
                              scope.row.unitConvertCoefficient > 1 &&
                              scope.row.qtyOperateMode === 2
                            "
                          >
                            <el-form-item>
                              <el-input-number
                                style="width: 100%; margintop: 18px"
                                v-model.lazy="scope.row.smallUnitQty"
                                clearable
                                controls-position="right"
                                :precision="0"
                                :disabled="true"
                                :min="0"
                                :max="smallMax(scope.row)"
                              />
                            </el-form-item>
                            <div class="page-table-input-number-item-unite">
                              {{ scope.row.calcUnitName }}
                            </div>
                          </div>
                        </div>
                        <div
                          class="page-table-input-number-right"
                          v-if="scope.row.qtyOperateMode === 2"
                        >
                          {{ $fn.qtyFormatter(scope.row.qty) }}
                        </div>
                      </div>
                    </el-form-item>
                    <span
                      v-else-if="
                        scope.row.codeType === 2 || scope.row.codeType === 3
                      "
                      >{{ $fn.qtyFormatter(scope.row.qty) }}</span
                    >
                  </template>
                  <span v-else>{{ $fn.qtyFormatter(scope.row.qty) }}</span>
                </template>
              </page-table>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
  </div>
  <SelectDepot
    v-if="selectDepotInfo.visible"
    v-model:showDialog="selectDepotInfo.visible"
    :checkBox="false"
    :query="selectDepotInfo.query"
    :highlightRow="true"
    :checkLock="true"
    :saveEmpty="true"
    @callback="selectDepotCallBack"
  />

  <SelectDepotStorage
    v-if="selectDepotStorageInfo.visible"
    v-model:showDialog="selectDepotStorageInfo.visible"
    :query="selectDepotStorageInfo.query"
    :excludeQueryList="selectDepotStorageInfo.excludeQueryList"
    :showPrice="$permission('consignConsumeConfirmOrder:price')"
    :orderId="orderId"
    @callback="selectDepotStorageCallBack"
  />

  <select-individual
    v-if="individualInfo.visible"
    v-model:visible="individualInfo.visible"
    v-model:leftQueryObj="individualInfo.leftQuery"
    v-model:rightQueryObj="individualInfo.rightQuery"
    v-model:infoList="individualInfo.productInfo"
    :requestRightList="!!orderId"
    :left-table-key="individualInfo.leftTableKey"
    v-model:rightApi="individualInfo.rightApi"
    v-model:leftApi="individualInfo.leftApi"
    v-model:rightVo="individualInfo.rightVo"
    :showPrice="$permission('consignConsumeConfirmOrder:price')"
    :orderId="orderId"
    @callback="selectedProductDetails"
  />
  <!-- 选择部门 -->
  <select-dept
    v-if="deptInfo.visible"
    v-model:showDialog="deptInfo.visible"
    :query="deptInfo.query"
    @callback="selectDeptCallback"
    :checkBox="false"
    :highlightRow="true"
    :saveEmpty="true"
  />
  <SelectSupplier
    v-if="selectProductSupplier.visible"
    v-model:show-dialog="selectProductSupplier.visible"
    v-model:query="selectProductSupplier.query"
    :check-box="false"
    :highlight-row="true"
    :saveEmpty="true"
    :api="selectProductSupplier.api"
    @callback="selectSupplierCallback"
  />
</template>

<script setup name="consignConsumeConfirmOrderModify">
import SelectDepotStorage from './selectProduct'
import selectIndividual from './individual'
import { getSupplierPage } from '@/api/core'
import {
  consumeDetailsConsignConsumeConfirmDetails,
  getConsignConsumeConfirmOrderById,
  getConsumeOrderDetailCustomizeListPage,
  createConsignConsumeConfirmOrder,
  createConsignConsumeConfirmOrderAndSave,
  updateConsignConsumeConfirmOrder,
  getConsignConsumeConfirmDetailsCustomizeListAll,
} from '@/api/stock'
import { getCustomizeSetting } from '@/api/customize'
import {
  setDisableTime,
  _getCurrentFiscalPeriod,
} from '@/common/js/dateOperation'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible', 'title', 'orderId', 'tableRow'])

const systemConfig = ref(proxy.$store.state.permission.systemConfig)
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {
      needAvailableConfirmQty: true,
    },
  },
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'removeProduct' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  map: new Map(),
  isSysGroup: true, //新增修改页是否有后端合并
  sysGroup: [], //新增修改页后端合并项
  selections: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '个体操作',
        event: _selectIndividual,
        show: true,
        ifRender: ifRenderValue,
      },
      {
        label: '删除',
        event: removeProduct,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
//表单相关
const formInfo = ref({
  ref: null,
  data: {
    depotName: proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
          '1'
        ) !== -1
        ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceName
        : ''
      : '',
    depotId: proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
          '1'
        ) !== -1
        ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
        : ''
      : '',
    deptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : '',
    deptName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : '',
    consumeDeptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : '',
    consumeDeptName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : '',
    supplierName: proxy.$store.state.user.userInfo.supplierName
      ? proxy.$store.state.user.userInfo.supplierName.name
      : '',
    supplierId: proxy.$store.state.user.userInfo.supplierName
      ? proxy.$store.state.user.userInfo.supplierName.id
      : -2,
  },
  fieldList: [
    { label: '消耗仓库', value: 'depotName', type: 'slot' },
    {
      label: '出库部门',
      value: 'deptName',
      type: 'input',
      disabled: true,
    },
    {
      label: '消耗部门',
      value: 'consumeDeptName',
      type: 'slot',
    },
    { label: '供应商', value: 'supplierName', type: 'slot' },
    {
      label: '来源消耗单',
      value: 'consumeOrderNo',
      type: 'input',
      disabled: true,
      show: false,
    },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      clearable: false,
    },
  ],
  rules: {
    depotName: [
      { required: true, message: '请选择消耗仓库', trigger: 'change' },
    ],
    consumeDeptName: [
      { required: true, message: '请选择消耗部门', trigger: 'change' },
    ],
    businessDate: [
      { required: true, message: '请选择业务日期', target: 'blur' },
    ],
  },
  labelWidth: '120px',
})
const selectDepotInfo = ref({
  visible: false,
  query: {
    depotAuth: 'id',
    status: 1,
    useTypeId: 1,
  },
})
const selectDepotStorageInfo = ref({
  visible: false,
  excludeQueryList: [], //库存产品左侧过滤配置
  query: {
    depotId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: null,
    },
    consumeDeptId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: null,
    },
    orderId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: null,
    },
    supplierId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: null,
    },
    orderNo: {
      queryType: 'IN',
      queryCategory: 'AND',
      value: null,
    },
  },
})
const individualInfo = ref({
  visible: false,
  selectObj: {}, //库存产品弹窗左边后端合并项
  productInfo: {}, //个体操作的当前这条数据
  leftQuery: {}, //个体弹窗左边数据查询条件
  rightQuery: {}, //个体弹窗右边数据查询条件
  leftTableKey:
    'consighConsumeQueryProductRight-com.slip.spd.entity.vo.stock.ConsumeOrderDetailVO',
  rightApi: getConsignConsumeConfirmDetailsCustomizeListAll, //个体弹窗右边数据接口
  leftApi: getConsumeOrderDetailCustomizeListPage, //个体弹窗左边数据接口
  rightVo: {}, //个体弹窗右边配置
})
const deptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
    status: '1',
  },
})
const selectProductSupplier = ref({
  visible: false,
  api: getSupplierPage,
  query: {
    // supplierAuth: 'supplierId',
    idNotIn: '',
  },
})
const slipSelectRequest = ref(true)
const formRefs = ref(undefined)

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canAddProduct = computed(() => {
  return formInfo.value.data.consumeDeptId && formInfo.value.data.depotId
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})

watch(
  () => tableInfo.value.data,
  (val) => {
    if (val.length && !tableInfo.value.isSysGroup) {
      tableInfo.value.data.forEach((row) => {
        let smallUnitQty = parseFloat(row.smallUnitQty || 0)
        let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
        let largeUnitQty = parseFloat(row.largeUnitQty || 0)
        let calcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
          smallUnitQty
        )
        let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
        row['calcQty'] = calcQty
        row['qty'] = qty
        row.sumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(calcQty, parseFloat(row.price)),
          unitConvertCoefficient
        )
        if (row.details && row.details.length) {
          row.details[0].qty = qty
          row.details[0].calcQty = calcQty
          row.details[0].largeUnitQty = largeUnitQty
          row.details[0].smallUnitQty = smallUnitQty
          row.details[0].sumAmount = row.sumAmount
        }
      })
    }
  },
  {
    deep: true,
  }
)

onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  proxy.$nextTick(() => {
    if (!props.orderId) {
      formInfo.value.fieldList = formInfo.value.fieldList.filter(
        (item) => item.value !== 'orderNo'
      )
    }
  })
})
let disStartDate = ref('')
let disEndDate = ref('')
setDisableTime(formInfo.value.fieldList, disStartDate, disEndDate)
async function setBusinessDate() {
  formInfo.value.data.businessDate = await _getCurrentFiscalPeriod(
    formInfo.value.fieldList,
    proxy,
    disStartDate,
    disEndDate
  )
}

createData()
function createData() {
  let obj = {
    qty: {
      label: '消耗数量',
      value: 'qty',
      type: 'slot',
      minWidth: '250px',
    },
    price: {
      label: '单价',
      value: 'price',
      minWidth: '150px',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('consignConsumeConfirmOrder:price'),
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('consignConsumeConfirmOrder:price'),
      hidden: true,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      permission: !proxy.$permission('consignConsumeConfirmOrder:price'),
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
  getInvdividualRightCustomize()
}
function openSupplierWindow() {
  selectProductSupplier.value.visible = true
  selectProductSupplier.value.query.idNotIn =
    formInfo.value.data['supplierId'] == -2
      ? ''
      : formInfo.value.data['supplierId']
}
function selectSupplierCallback(data) {
  if (data && data.supplierId) {
    formInfo.value.data['supplierId'] = data.supplierId
    formInfo.value.data['supplierName'] = data.supplierName
    tableInfo.value.data = []
    tableInfo.value.map = new Map()
    selectDepotStorageInfo.value.excludeQueryList = []
  } else {
    formInfo.value.data['supplierId'] = -2
    formInfo.value.data['supplierName'] = ''
    tableInfo.value.data = []
    tableInfo.value.map = new Map()
    selectDepotStorageInfo.value.excludeQueryList = []
  }
}
function selectConsumeDept() {
  deptInfo.value.visible = true
}
function selectDeptCallback(row) {
  if (row) {
    formInfo.value.data.consumeDeptName = row.name
    formInfo.value.data.consumeDeptId = row.id
    tableInfo.value.data = []
    tableInfo.value.map = new Map()
    selectDepotStorageInfo.value.excludeQueryList = []
  } else {
    formInfo.value.data.consumeDeptName = ''
    formInfo.value.data.consumeDeptId = ''
    tableInfo.value.data = []
    tableInfo.value.map = new Map()
    selectDepotStorageInfo.value.excludeQueryList = []
  }
}
function showFinanceFieldListItem(show, nameValue) {
  let fieldList = formInfo.value.fieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}
function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.availableConfirmCalcQty / row.unitConvertCoefficient)
  } else {
    return row.stockAvailableQty
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(
    row.availableConfirmCalcQty / row.unitConvertCoefficient
  )
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.availableConfirmCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  let largeUnitQty = parseInt(
    row.availableConfirmCalcQty / row.unitConvertCoefficient
  )
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(
        row.availableConfirmCalcQty % row.unitConvertCoefficient
      )
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
      }
    }
  }
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}
function ifRenderValue() {
  return tableInfo.value.isSysGroup
}
async function setData(data, newKey, type = false) {
  //个体操作弹窗扫码回调设置数据
  let newData
  if (!type) {
    let map = await proxy.$fn.getDepotStorage(
      data,
      tableInfo.value.sysGroup,
      tableInfo.value.map,
      getConsignConsumeConfirmDetailsCustomizeListAll,
      props.orderId,
      individualInfo.value.rightVo,
      'scan'
    )
    tableInfo.value.map = map
    tableInfo.value.data = [...map.values()]
    newData = map.get(newKey)
  } else {
    newData = tableInfo.value.map.get(newKey)
  }
  await getIndividualInfoQuery(newData)
}
async function _selectIndividual(data) {
  //选择个体
  await getIndividualInfoQuery(data)
  individualInfo.value.visible = true
}
async function getIndividualInfoQuery(data) {
  // 设置个体操作参数
  for (let key in individualInfo.value.selectObj) {
    individualInfo.value.selectObj[key].value = data[key]
  }
  individualInfo.value.leftQuery.id = {
    queryType: 'NOT_IN',
    queryCategory: 'AND',
    value: data.groupConcatDepotStockIds,
  }
  individualInfo.value.leftQuery.productId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: data.productId,
  }
  individualInfo.value.leftQuery.depotId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: formInfo.value.data.depotId,
  }
  individualInfo.value.leftQuery.consumeDeptId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: formInfo.value.data.consumeDeptId,
  }
  individualInfo.value.leftQuery.orderNo = {
    queryType: 'IN',
    queryCategory: 'AND',
    value: formInfo.value.data.consumeOrderNo || '',
  }
  individualInfo.value.leftQuery = {
    ...individualInfo.value.leftQuery,
    ...individualInfo.value.selectObj,
  }
  individualInfo.value.rightQuery.id = {
    queryType: 'IN',
    queryCategory: 'AND',
    value: data.groupConcatIds,
  }
  individualInfo.value.rightQuery.orderId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: props.orderId,
  }
  individualInfo.value.productInfo = data
}
async function selectedProductDetails(data) {
  //个体返回
  if (data.details && data.details.length) {
    tableInfo.value.map.set(data.key, data)
    let index = tableInfo.value.data.findIndex((item) => item.key === data.key)
    if (index !== -1) {
      tableInfo.value.data[index] = data
    }
  } else {
    removeProduct(data)
  }
}
function getMain() {
  getConsignConsumeConfirmOrderById(props.orderId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
    }
  })

  filterInfo.value.query.queryMap.orderId.value = props.orderId
  getList()
}
function getList() {
  //修改请求明细信息
  getConsignConsumeConfirmDetailsCustomizeListAll(filterInfo.value.query).then(
    (resp) => {
      if (resp && resp.success && resp.data.length) {
        let data = resp.data
        data.forEach((item) => {
          //将返回的数据变成Map形式
          let key = []
          tableInfo.value.sysGroup.forEach((row) => {
            let obj = {}
            obj.columnName = row.columnName
            obj.asTbName = row.asTbName
            obj.value = item[row.key]
            key.push(obj)
          })
          item.key = JSON.stringify(key)
          if (!tableInfo.value.isSysGroup) {
            item.groupConcatDepotStockIds = item.consumeDetailId.toString()
            item.groupSize = 1
            let row = proxy.$fn.deepClone(item)
            delete row.key
            item.details = [row]
          }
          tableInfo.value.map.set(item.key, item)
        })
        tableInfo.value.data = resp.data
        setBusinessDate()
      }
    }
  )
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function saveAndSubmit() {
  save(true)
}
function save(isSaveAndSubmit) {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const newDetails = tableInfo.value.data.filter(
      (row) => row.productId && row.qty > 0
    )
    if (!newDetails.length) {
      proxy.$message({
        message: '请添加有效的产品',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    let details = proxy.$fn.filterBlacklist(newDetails)
    let params = { ...formInfo.value.data, mergeDetails: details }
    const api = props.orderId
      ? updateConsignConsumeConfirmOrder
      : isSaveAndSubmit === true
      ? createConsignConsumeConfirmOrderAndSave
      : createConsignConsumeConfirmOrder
    api(params).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emits('returnModify', false)
        if (resp && resp.success) {
          tableInfo.value.data = []
          selectDepotStorageInfo.value.excludeQueryList = []
          tableInfo.value.map = new Map()
        }
      }
    })
  })
}
//选择仓库
function selectStoreDepot() {
  selectDepotInfo.value.visible = true
}
function selectDepotCallBack(data = undefined) {
  if (data && data.id) {
    formInfo.value.data.depotId = data.id
    formInfo.value.data.depotName = data.name
    formInfo.value.data.deptName = data.deptName || ''
    formInfo.value.data.deptId = data.deptId || ''
    formInfo.value.data.consumeDeptName = data.deptName || ''
    formInfo.value.data.consumeDeptId = data.deptId || ''
    tableInfo.value.data = []
    tableInfo.value.map = new Map()
    selectDepotStorageInfo.value.excludeQueryList = []
  } else {
    formInfo.value.data.depotId = ''
    formInfo.value.data.depotName = ''
    formInfo.value.data.name = ''
    formInfo.value.data.deptId = ''
    formInfo.value.data.consumeDeptName = ''
    formInfo.value.data.consumeDeptId = ''
    tableInfo.value.data = []
    tableInfo.value.map = new Map()
    selectDepotStorageInfo.value.excludeQueryList = []
  }
}
//选择库存产品
function addProduct() {
  let keys = [...tableInfo.value.map.keys()]
  let excludeQueryList = []
  if (keys.length && tableInfo.value.sysGroup.length) {
    excludeQueryList = keys.map((item) => JSON.parse(item))
  }
  selectDepotStorageInfo.value.excludeQueryList = excludeQueryList //库存产品左侧过滤配置
  selectDepotStorageInfo.value.query.depotId.value = formInfo.value.data.depotId
  selectDepotStorageInfo.value.query.supplierId.value =
    formInfo.value.data.supplierId == -2 ? '' : formInfo.value.data.supplierId
  selectDepotStorageInfo.value.query.consumeDeptId.value =
    formInfo.value.data.consumeDeptId
  selectDepotStorageInfo.value.query.orderNo.value =
    formInfo.value.data.consumeOrderNo || ''
  selectDepotStorageInfo.value.visible = true
}
async function selectDepotStorageCallBack(rows = []) {
  //库存产品返回
  let map = await proxy.$fn.getDepotStorage(
    rows,
    tableInfo.value.sysGroup,
    tableInfo.value.map,
    getConsignConsumeConfirmDetailsCustomizeListAll, //个体弹窗右边数据接口
    props.orderId,
    individualInfo.value.rightVo //个体弹窗右边表格配置
  )
  tableInfo.value.map = map
  tableInfo.value.data = [...map.values()]
}
//删除产品
function removeProduct(row = undefined) {
  if (row && row.key) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (item) => item.key !== row.key
    )
    let key = row.key
    tableInfo.value.map.delete(key)
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.selections.forEach((row) => {
          for (let [key, value] of tableInfo.value.map) {
            if (key === row.key) {
              tableInfo.value.map.delete(key)
            }
          }
        })
        tableInfo.value.data = tableInfo.value.data.filter((row) => {
          return !tableInfo.value.selections.includes(row)
        })
      })
  }
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'consignConsumeConfirmOrderDetailModify-com.slip.spd.entity.vo.stock.ConsignConsumeConfirmOrderDetailVO',
  }
  tableInfo.value.isSysGroup = false
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          tableInfo.value.isSysGroup = true
        }
      }
      slipSelectRequest.value = _slipSelectRequest
      filterInfo.value.query.customizeUserVO = data
      getDeoptLeftCustomize()
    }
  })
}
function getDeoptLeftCustomize() {
  //库存产品弹窗左侧配置
  let param = {
    tableKey:
      'consighConsumeQueryProductLeft-com.slip.spd.entity.vo.stock.ConsumeOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      let arr = []
      let obj = {}
      if (tableInfo.value.isSysGroup) {
        for (let key in data.detail) {
          if (data.detail[key].sysGroupLevel > 0) {
            arr.push({
              columnName: data.detail[key].columnName,
              asTbName: data.detail[key].asTbName,
              key: key,
            })
            obj[key] = {
              queryType: 'EQUALS',
              queryCategory: 'AND',
              ignoreEmptyValue: false,
              value: null,
            }
          }
        }
      } else {
        arr.push({
          columnName: data.detail.id.columnName,
          asTbName: data.detail.id.asTbName,
          key: 'consumeDetailId',
        })
        obj['consumeDetailId'] = {
          queryType: 'EQUALS',
          queryCategory: 'AND',
          value: null,
        }
      }
      individualInfo.value.selectObj = obj
      tableInfo.value.sysGroup = arr
      if (props.orderId) {
        getMain()
        showFinanceFieldListItem(true, 'consumeOrderNo')
      } else if (props.tableRow && props.tableRow.id) {
        showFinanceFieldListItem(true, 'consumeOrderNo')
        formInfo.value.data['deptName'] = props.tableRow.deptName
        formInfo.value.data['deptId'] = props.tableRow.deptId
        formInfo.value.data['depotName'] = props.tableRow.depotName
        formInfo.value.data['depotId'] = props.tableRow.depotId
        formInfo.value.data['consumeDeptName'] = props.tableRow.consumeDeptName
        formInfo.value.data['consumeDeptId'] = props.tableRow.consumeDeptId
        formInfo.value.data['consumeOrderId'] = props.tableRow.id
        formInfo.value.data['consumeOrderNo'] = props.tableRow.orderNo
        selectDepotStorageInfo.value.query.orderId.value = props.tableRow.id
        getDetailsList()
        setBusinessDate()
      } else {
        setBusinessDate()
      }
    }
  })
}
function getDetailsList() {
  //从消耗查询过来的待确认数据
  let query = {
    queryMap: {},
    customizeUserVO: {
      ...filterInfo.value.query.customizeUserVO,
    },
    queryParams: {
      confirmQtyGt: 0,
      orderId: props.tableRow.id,
    },
  }
  consumeDetailsConsignConsumeConfirmDetails(query).then((resp) => {
    if (resp && resp.success) {
      let data = resp.data
      data.forEach((item) => {
        //将返回的数据变成Map形式
        let key = []
        tableInfo.value.sysGroup.forEach((row) => {
          let obj = {}
          obj.columnName = row.columnName
          obj.asTbName = row.asTbName
          obj.value = item[row.key]
          key.push(obj)
        })
        item.key = JSON.stringify(key)
        if (!tableInfo.value.isSysGroup) {
          item.groupConcatDepotStockIds = item.consumeDetailId.toString()
          item.groupSize = 1
          let row = proxy.$fn.deepClone(item)
          delete row.key
          item.details = [row]
        }
        tableInfo.value.map.set(item.key, item)
      })
      tableInfo.value.data = resp.data
    }
  })
}
function getInvdividualRightCustomize() {
  //获取个体弹窗右边配置
  let param = {
    tableKey:
      'consignConsumeConfirmOrderDetailModifySingle-com.slip.spd.entity.vo.stock.ConsignConsumeConfirmOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      individualInfo.value.rightVo = res.data
    }
  })
}
</script>

<style scoped lang="scss">
:deep(.page-table) > .el-table {
  overflow: hidden;
}
</style>
